//
//  MiddleManAddCustomerViewController.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/4/29.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//   经纪人－－－添加潜在客户

#define UIScrollViewHeight 600
#import "MiddleManAddCustomerViewController.h"
#import "UIView+circular.h"
#import "BrokerDataMange.h"
#import "AddLatentCusModel.h"
#import "MBProgressHUD+MJ.h"
#import "UserModal.h"
#import "StringTool.h"
#import "config.h"

#import "UIView+circular.h"
#import "SexView.h"
#import "CardView.h"

@interface MiddleManAddCustomerViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UITextViewDelegate,UIScrollViewDelegate>
@property (strong, nonatomic) IBOutlet UIScrollView *mainView;

@property (nonatomic,strong)SexView *sexView;
@property (nonatomic,strong)CardView *cardView;

@property (weak, nonatomic) IBOutlet UIView *view1;
@property (weak, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UIView *view3;
@property (weak, nonatomic) IBOutlet UIView *view4;
@property (weak, nonatomic) IBOutlet UIView *view5;
@property (weak, nonatomic) IBOutlet UIView *view6;

@property (weak, nonatomic) IBOutlet UIView *contentView;


@property (weak, nonatomic) IBOutlet UITextField *nameTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *idCardTextField;
@property (weak, nonatomic) IBOutlet UITextView *beizhuTextView;
@property (weak, nonatomic) IBOutlet UITextField *sexTextField;
@property (weak, nonatomic) IBOutlet UITextField *cardTypeTextField;

@property (strong, nonatomic) BrokerDataMange *dataManage;


@property (strong, nonatomic) NSArray *dataArray;

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) AddLatentCusModel *model;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;


- (IBAction)clickBtn:(UIButton *)sender;



@end

@implementation MiddleManAddCustomerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
}

-(AddLatentCusModel *)model
{
    if (!_model) {
        _model = [[AddLatentCusModel alloc]init];
    }
    return _model;
}
-(BrokerDataMange *)dataManage
{
    if (!_dataManage) {
        _dataManage = [[BrokerDataMange alloc]init];
    }
    return _dataManage;
}
-(void)initView
{
    
    [self.saveBtn viewToCircular];
    self.titleView.doneBtn.hidden = YES;
    if (self.state == vcState_add) {
        
        [self.titleView setMianTitle:@"添加客户"];
    }else
    {
        [self.titleView  setMianTitle:@"修改信息"];
    }
    self.mainView.delegate = self;
    self.beizhuTextView.delegate = self;
    
    [self.view1 viewmakeline];
    [self.view2 viewmakeline];
    [self.view3 viewmakeline];
    [self.view4 viewmakeline];
    [self.view5 viewmakeline];
    [self.view6 viewmakeline];
    
    self.phoneTextField.enabled = YES;
    
    if (self.state == vcState_edit) {
      
        if (![StringTool isBlankString:self.custModel.consumerName]) {
            self.nameTextFiled.text = self.custModel.consumerName;
        }else
        {
            self.nameTextFiled.placeholder = @"";
            self.nameTextFiled.text = @"";
        }
        
        self.phoneTextField.enabled = NO;
        if (![StringTool isBlankString:self.custModel.consumerName]) {
            self.phoneTextField.text = self.custModel.consumerMobile;
        }else
        {
            self.phoneTextField.placeholder = @"";
            self.phoneTextField.text = @"";
        }
        
        if (self.custModel.sex == 0 ) {
            self.sexTextField.text = @"女";
        }
        else
        {
            self.sexTextField.text = @"男";
        }
        
        if (self.custModel.idCardType == 0) {
            self.cardTypeTextField.text = @"身份证";
        }else if (self.custModel.idCardType == 1)
        {
            self.cardTypeTextField.text = @"港澳通行证";
        }else if (self.custModel.idCardType == 2)
        {
            self.cardTypeTextField.text = @"护照";
        }
        
        if (![StringTool isBlankString:self.custModel.idCard]) {
            self.idCardTextField.text = self.custModel.idCard;
        }
        if (![StringTool isBlankString:self.custModel.memo]) {
            self.beizhuTextView.text = self.custModel.memo;
        }
    }

    
    self.sexView = [SexView createView];
    self.sexView.sureBtn.tag = 100;
    [self.sexView showhighlighted:self.sexTextField.text];
    [self.sexView.sureBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.cardView = [CardView createView];
    self.cardView.sureBtn.tag = 101;
    [self.cardView showhighlighted:self.cardTypeTextField.text];
    [self.cardView.sureBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)btnOnclick:(UIButton *)btn
{
    if (btn.tag == 100) {
        
        [self.sexView hide];
        self.sexTextField.text = [self.sexView getInof];
    }else
    {
        self.cardTypeTextField.text = [self.cardView getInfo];
        [self.cardView hide];
    }
}

- (IBAction)clickBtn:(UIButton *)sender
{
    NSInteger tag = sender.tag;
    
    switch (tag) {
        case 0://选择性别
        {
            [self.view endEditing:YES];
            [self.sexView showhighlighted:self.sexTextField.text];
            [self.sexView showInView:self.view];
        }
            break;
        case 1://选择证件号
        {
            [self.view endEditing:YES];
            [self.cardView showhighlighted:self.cardTypeTextField.text];
            [self.cardView showInView:self.view];
        }
            break;
        case 2://保存信息
        {
            if ([self checkInfo]) {
                [self upData];
            }
            
        }
            break;
        default:
            break;
    }
}
#pragma mark 判读手机号
-(BOOL)checkPhone
{
    if ([StringTool isBlankString:_phoneTextField.text])
    {
        [MBProgressHUD showError:@"请输入手机号!"];
        return NO;
    }else if (![self validateMobile:_phoneTextField.text])
    {
        [MBProgressHUD showError:@"请输入正确的手机号!"];
            return NO;
        }
    return YES;
    
}
#pragma mark 判读证件信息
-(BOOL)checkCardInfo
{
    if (![StringTool isBlankString:self.cardTypeTextField.text]) {
        
        if ([StringTool isBlankString:self.idCardTextField.text]) {
            [MBProgressHUD showError:@"请输入证件号"];
            return NO;
        }
    }else{
        if (![StringTool isBlankString:self.idCardTextField.text]) {
            [MBProgressHUD showError:@"请选择证件类型"];
            return NO;
        }
    }
    return YES;
}
#pragma mark 判断输入不空
-(BOOL)checkInfo
{
    if ([StringTool isBlankString:_nameTextFiled.text]) {
        [MBProgressHUD showError:@"请输入用户名!"];
        return NO;
    }else if(![self checkPhone]){
        return NO;
    }else if (![self checkCardInfo])
    {
        return NO;
    }
    self.model.name = _nameTextFiled.text;
    self.model.name = [StringTool isBlankString:_nameTextFiled.text]? @"":_nameTextFiled.text;
    
    self.model.mobile = [StringTool isBlankString:_phoneTextField.text]? @"":_phoneTextField.text;
    self.model.idCard = [StringTool isBlankString:_idCardTextField.text]? @"":_idCardTextField.text;
    
    if (![StringTool isBlankString:_sexTextField.text]) {
        
        if ([_sexTextField.text isEqualToString:@"男"]) {
            self.model.sex = @"1";
        }else if ([_sexTextField.text isEqualToString:@"女"])
        {
            self.model.sex = @"0";
        }

    }else
    {
        self.model.sex = @"";
    }
    
    
    if (![StringTool isBlankString:_cardTypeTextField.text]) {
        if ([_cardTypeTextField.text isEqual:@"身份证"]) {
            self.model.idCardType = @"0";
        }else if ([_cardTypeTextField.text isEqual:@"港澳通行证"])
        {
            self.model.idCardType = @"1";
        }else if ([_cardTypeTextField.text isEqual:@"护照"])
        {
            self.model.idCardType = @"2";
        }

    }else
    {
        self.model.idCardType = @"";
    }
    
    if ([StringTool isBlankString:_beizhuTextView.text]) {
        self.model.memo = @"";
    }else
    {
        self.model.memo = _beizhuTextView.text;
    }
    
    return YES;
}

#pragma mark 上传数据
-(void)upData
{
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    
    __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       
        NSString *customerId = [NSString stringWithFormat:@"%zd",[UserModal shareUserModel].userId];
        ResulteMod *mod;
        if (bself.state == vcState_add) {//添加潜在客户
            mod = [bself.dataManage ddpotentialconsumerWithPotentialModel:bself.model withcustomerId:customerId];
        }else //修改潜在客户
        {
            mod = [bself.dataManage updatepotentialconsumerWithPotentialModel:bself.model withcustomerId:bself.custModel.consumerId];
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            
            if (mod.resltState == ResultFail) {
                
                NSString *str = ![StringTool isBlankString:mod.resultDic[@"message"]]?mod.resultDic[@"message"]:[StringTool isBlankString:mod.resultCode]?@"网络错误":[NSString stringWithFormat:@"网络错误%@",mod.resultCode];
                
                 [MBProgressHUD showError:str];
                
            }else if (mod.resltState == ResultNetError)
            {
                 [MBProgressHUD showError:@"网络错误"];
            }else
            {
                 if (bself.state == vcState_add)
                 {
                      [MBProgressHUD showSuccess:@"添加成功"];
                 }else
                 {
                      [MBProgressHUD showSuccess:@"修改成功"];
                 }
               
                [bself.nav popViewControllerAnimated:YES];
            }
            
        });
    });
}
#pragma mark 初始化下拉框
-(void)initTableViewWithflag:(NSInteger )flag
{
    
    CGFloat tableViewX;
    CGFloat tableViewY;
    CGFloat tableViewW;
    CGFloat tableViewH = 44*self.dataArray.count;
    if (flag == 0) {
         tableViewX = self.view3.frame.origin.x;
         tableViewY = self.view3.frame.origin.y + self.view3.frame.size.height;
         tableViewW = self.view3.frame.size.width;
        
         self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(tableViewX, tableViewY, tableViewW, tableViewH)];
        
        self.tableView.tag = 100;
        
    }else if (flag == 1)
    {
        tableViewX = self.view4.frame.origin.x;
        tableViewY = self.view4.frame.origin.y + self.view4.frame.size.height;
        tableViewW = self.view4.frame.size.width;
        
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(tableViewX, tableViewY, tableViewW, tableViewH)];
        
        self.tableView.tag = 101;
    }
    
   
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView viewToCircular];
    [self.contentView addSubview:self.tableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"xuanzecell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
    cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView.tag == 100) {
        _sexTextField.text = [self.dataArray objectAtIndex:indexPath.row];
    }else
    {
        _cardTypeTextField.text = [self.dataArray objectAtIndex:indexPath.row];
    }
    if (self.tableView != nil) {
         [self.tableView removeFromSuperview];
        self.tableView = nil;
    }

}



- (void) animateTextField: (UIView*) textField up: (BOOL) up
{
    
    CGRect dd =  [textField.superview convertRect:textField.frame toView:self.tableView];
    
    int tvbotY = dd.size.height+dd.origin.y;
    int mid  = PMH-250-tvbotY;
    
    if (mid<0&&up==true) {
        
        const float movementDuration = 0.3f;
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        
        CGRect buf = self.tableView.frame;
        buf.origin.y = up ? mid : 0;
        [self.tableView setFrame:buf];
        
        [UIView commitAnimations];
    }else if(up==false){
        
        [self viewRest];
    }
}



-(void)viewRest{
    
    
    const float movementDuration = 0.3f;
    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    
    CGRect buf = self.view.frame;
    buf.origin.y =  0;
    [self.tableView setFrame:buf];
    
    [UIView commitAnimations];
    
    [self.tableView endEditing:YES];
}



#pragma mark scrollVIew delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self viewRest];
}



#pragma et delegare
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self animateTextField:textField up:false];
    
    [textField resignFirstResponder];
    
    [self viewRest];
    return  YES;
}


- (void)backAction
{
    [self.nav popViewControllerAnimated:YES];
}

#pragma mark textView的代理
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
{
    
   [self animateTextField:textView up:true];
    
    return YES;
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        
        [self viewRest];
        
        return NO;
    }
    
    return YES;
}

@end
